#include "ustandard/ustandard.h"

#if 0
#define PATH "./p2pclient_record -sr"
#define PS_PATH "p2pclient"
#define NUM_PROC    6
#define SEC_SLEEP   5
#endif

#define LEN     1024
char kpath[LEN];
char kps_path[LEN];
int knum_proc;
int ksecs_sleep;



#define len_datetime    128
char ktime[len_datetime];

static int process_running_num(const char* path);
int main()
{
    int ret = 0;

    ustrcpy(kpath, LEN, "please_define_procname");
    ustrcpy(kps_path, LEN, "please_define_ps_procname");
    knum_proc = 6;
    ksecs_sleep = 6;

    char line[LEN] = {0};
    FILE* fp = fopen("applaunch.conf", "r");
    const char* strkey;
    if(NULL != fp) {
        while(NULL != fgets(line, LEN-1, fp)) {
            strkey = "execute=";
            if(0 == strncmp(line, strkey, strlen(strkey))) {
                ustrcpy(kpath, LEN, line+strlen(strkey));
            }

            strkey = "ps_key=";
            if(0 == strncmp(line, strkey, strlen(strkey))) {
                ustrcpy(kps_path, LEN, line+strlen(strkey));
            }

            strkey = "number=";
            if(0 == strncmp(line, strkey, strlen(strkey))) {
                knum_proc = atol(line+strlen(strkey));
            }

            strkey = "secs_sleep=";
            if(0 == strncmp(line, strkey, strlen(strkey))) {
                ksecs_sleep = atol(line+strlen(strkey));
            }
        }

        fclose(fp);
        fp = NULL;
    }

    ustrtrim_chars(kpath, 0, 1, UST_CHARS_CRLF, UST_N_CHARS_CRLF);
    ustrtrim_chars(kps_path, 0, 1, UST_CHARS_CRLF, UST_N_CHARS_CRLF);
    printf("path=[%s], ps_path=[%s], num_proc=[%d], secs_sleep=[%d].\n", 
            kpath, kps_path, knum_proc, ksecs_sleep);

    #define LEN_CMD 1024
    char cmd[LEN_CMD];

    while(1) {
        int n_process_running = process_running_num(kps_path);
        if(n_process_running < knum_proc) {
            int n_launch = urandft(0, knum_proc-n_process_running);
            fprintf(stdout, "launch app num : %d.\n", n_launch);
            while(n_launch--) {
                ustrtime_now(ktime, len_datetime, NULL);
                fprintf(stdout, "launch app at : %s.\n", ktime);
                snprintf(cmd, LEN_CMD, "%s > /dev/null &", kpath);
                system(cmd);
                usleep(100*1000);
            }
        }

        sleep(ksecs_sleep);
    }

    return ret;
}


int process_running_num(const char* path)
{
    int retn = 0;

    FILE* fp = popen("ps -a", "r");
    assert(NULL != fp);
    
#define len_str     (1024)
    char str[len_str] = {0};
    fread(str, 1, len_str, fp);
    pclose(fp);

    printf("%s\n", str);

    char* s = str;
    char* tmp;

    while(NULL != (tmp = strstr(s, path)) && ++retn && NULL != (s = tmp+1));

    printf("process_running_num : %d\n", retn);

    return retn;
}
